import router from '../router'
import store from '../store'
import getDeviceInfo from './deviceInfo'
import axios from 'axios'
import consts from './consts'
import * as utils from './utils'
import {
  accessLog
} from './dataBuried'

// 刚进来的时候判断有没有tfrom 有就存到sessionStorage

let tfrom = utils.getUrlString('tfrom')
if (tfrom) {
  window.sessionStorage.setItem('tfrom', tfrom)
}

const noShareDataPages = ['addbrand', 'addsuccess', 'applyReward', 'applyRewardSuccess', 'feedBack', 'feedBackSuccess', 'teachVideo', 'voteRules', 'shareDemo', 'process']
let configUrl = ''
let configData
let shareDesc
let shareImg
let shareTitle
let votedShareImg
let votedShareTitle
let votedShareDesc
let cfrom
let cstatus // 分享数据埋点参数
let isPageCfrom = false // 是不是需要埋点回调的页面
let page

router.beforeEach((to, from, next) => {
  page = to.name
  // 与分享无关  为了解决ios 刷新页面  导致的 添加品牌 / 申请奖牌 后退至揭榜页  数据不清空问题
  if (to.name === 'newEndPage' || to.name === 'oldEndPage' || to.name === 'mediaForward') {
    window.sessionStorage.removeItem('applyForm')
    window.sessionStorage.removeItem('brandFrom')
  }
  // 切换页面初始化埋点标志
  isPageCfrom = false
  // 数据埋点逻辑
  if ((to.name === 'index' || to.name === 'newEndPage' || to.name === 'oldEndPage') && utils.getUrlString('catid')) {
    getStatus(utils.getUrlString('catid'))
    isPageCfrom = true
  }
  if (getDeviceInfo().isWeiXin && getDeviceInfo().isIOS && to.path !== window.location.pathname && window.sessionStorage.getItem('replaced') && to.name !== 'companyDetails') {
    // 在重定向的情况下才刷新页面
    // 点击企业详情刷新bug
    setTimeout(() => {
      // 此处不可使用location.replace
      window.location.assign(to.fullPath)
    }, 10)
  } else {
    next()
  }
})

router.afterEach(to => {
  setTimeout(() => {
    // 现在不管是安卓还是ios 每次进入页面都去重新获取签名
    configUrl = window.location.href
    if (noShareDataPages.indexOf(to.name) !== -1 && window.sessionStorage.getItem('shareImg')) {
      // 没有掉接口的页面 如果有之前的分享数据的话 用之前的分享数据去初始化
      getSignature(window.sessionStorage.getItem('shareImg'), window.sessionStorage.getItem('shareTitle'), window.sessionStorage.getItem('shareDesc'))
    }
  }, 10)
})

// 数据埋点需要行业状态
function getStatus(catid) {
  axios
    .post(consts.baseUrl + 'category_status.php?catid=' + catid)
    .then(data => {
      cstatus = parseInt(data.data.category_status)
      if (cstatus === 0) {
        cstatus = 7
      }
      if (page === 'oldEndPage') {
        cstatus = 6
      }
    })
    .catch(err => {
      console.log(err)
    })
}

export const getSignature = (pImg, pTitle, pDesc) => {
  if (getDeviceInfo().isWeiXin) {
    if (store.state.voted && !votedShareImg) {
      // 存储投过票的分享信息
      votedShareImg = pImg
      votedShareTitle = pTitle
      votedShareDesc = pDesc
    }
    if (router.history.current.name === 'index' && votedShareImg && store.state.voted) {
      // 如果投过票 又是在投票列表页 就用投过票的分享数据来初始化微信分享
      shareImg = votedShareImg
      shareTitle = votedShareTitle
      shareDesc = votedShareDesc
    } else {
      shareImg = pImg
      shareTitle = pTitle
      shareDesc = pDesc
      window.sessionStorage.setItem('shareImg', shareImg)
      window.sessionStorage.setItem('shareTitle', shareTitle)
      window.sessionStorage.setItem('shareDesc', shareDesc)
    }
    axios
      .get(consts.baseUrl + 'wx_get_signature.php?url=' + encodeURIComponent(configUrl))
      .then(data => {
        configData = data.data.res
        shareConfig()
      })
      .catch(err => {
        console.log(err)
      })
  }
}

export const clearVotedShareData = () => {
  // 在获取新的投票分享数据前 清除之前存的
  votedShareImg = ''
  votedShareTitle = ''
  votedShareDesc = ''
}

function shareConfig() {
  if (getDeviceInfo().isWeiXin && configData) {
    wx.config({
      debug: false,
      appId: configData.appid,
      timestamp: configData.timestamp,
      nonceStr: configData.nonceStr,
      signature: configData.signature,
      jsApiList: [
        // 需要调用的JS接口列表
        'checkJsApi', //判断当前客户端版本是否支持指定JS接口
        'onMenuShareTimeline', //分享给好友
        'onMenuShareAppMessage', //分享到朋友圈
        'onMenuShareQQ', //分享到QQ
        'onMenuShareQZone' //分享到QQ空间
      ]
    })
    wx.ready(() => {
      configShare()
    })
    wx.error(function () {})
  }
}

function configShare() {
  let route = router.history.current
  let catid = route.query.catid || route.params.catid
  let tfrom = window.sessionStorage.getItem('tfrom')
  let shareUrl
  if (catid) {
    if (route.name === 'successfulCaseDetail' && !route.query.catid) {
      // 成功案例详情页并且没有catid 说明是父级页面是没有catid的
      shareUrl = window.location.href + '?ctype=1'
    } else {
      shareUrl = window.location.protocol + '//' + window.location.host + '/?catid=' + catid + '&ctype=1'
    }
  } else {
    shareUrl = window.location.href + '?ctype=1'
  }
  if (tfrom && shareUrl.indexOf('tfrom') == -1) {
    shareUrl += '&tfrom=' + tfrom
  }
  let shareConfigData = {
    title: shareTitle,
    link: shareUrl,
    desc: shareDesc,
    imgUrl: shareImg,
    success: function () {
      configShare()
    }
  }
  // 列表页 埋点分享逻辑
  if (isPageCfrom) {
    wx.onMenuShareTimeline({
      title: shareTitle,
      link: shareUrl + '&cfrom=A7BsI&cstatus=' + cstatus,
      desc: shareDesc,
      imgUrl: shareImg,
      success: function () {
        configShare()
        accessLog('A7BsI', cstatus)
      }
    })
    wx.onMenuShareAppMessage({
      title: shareTitle,
      link: shareUrl + '&cfrom=xYj25&cstatus=' + cstatus,
      desc: shareDesc,
      imgUrl: shareImg,
      success: function () {
        configShare()
        accessLog('xYj25', cstatus)
      }
    })
  } else {
    // 非列表页
    wx.onMenuShareTimeline(shareConfigData)
    wx.onMenuShareAppMessage(shareConfigData)
  }

  wx.onMenuShareQQ(shareConfigData)
  wx.onMenuShareQZone(shareConfigData)
}